package org.changs.control.ui.carfile.video;

import android.app.AlertDialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import org.changs.aplug.utils.EmptyUtils;
import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.control.R;
import org.changs.control.databinding.ItemListBinding;
import org.changs.media.MediaFile;
import org.changs.media.MediaManager;

import java.util.List;

import aplug.utils.SwipeItemDelegate;

/**
 * 视频的适配器
 * Created by Administrator on 2017/8/24.
 */

public class VideoAdapter extends SimpleAdapter<MediaFile, ItemListBinding> {
    private Context context;
    private MediaManager mediaManager;
    SwipeItemDelegate delegate;

    public VideoAdapter(Context context, List<MediaFile> videos, RecyclerView rcyView, MediaManager mediaManager) {
        super(videos, R.layout.item_list);
        this.context = context;
        this.mediaManager = mediaManager;
        delegate = new SwipeItemDelegate(this, rcyView);
    }

    @Override
    public void onBindViewHolder(ItemListBinding binding, int position) {
        delegate.setDelegate(binding.swipeLayout);
        MediaFile video = getData().get(position);

        binding.tvName.setText(video.getName());
        binding.tvTime.setText(video.getTime());
        if (!EmptyUtils.isEmpty(video.getThumb())) {
            binding.image.setImageBitmap(video.getThumb());
        } else {
            binding.image.setBackgroundColor(context.getResources().getColor(R.color.transparent_half));
        }

        binding.btnDelete.setOnClickListener(v -> showDialog(video));
        binding.getRoot().setOnClickListener(v -> context.startActivity(VideoPlayAct.getIntent(context, video)));
    }

    private AlertDialog dialog;

    private void showDialog(MediaFile picture) {
        if (dialog == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_delete, null);
            dialog = new AlertDialog.Builder(context).setView(view).create();
            TextView textView = (TextView) view.findViewById(R.id.tv_content);
            textView.setText("确定删除该视频吗？");
            view.findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
        }
        dialog.show();
        dialog.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            mediaManager.delete(picture);
            dialog.dismiss();
            delegate.closeOpenedSwipeItemLayoutWithAnim();
        });
    }
}
